<template>
    <div class="parts-request-container">
      <h2>零部件申请</h2>
      
      <!-- 申请表单 -->
      <el-card class="request-card">
        <el-form :model="requestForm" :rules="rules" ref="requestFormRef" label-width="100px">
          <el-form-item label="零部件" prop="partId">
            <el-select 
              v-model="requestForm.partId" 
              placeholder="请选择零部件" 
              style="width: 100%"
              filterable
            >
              <el-option 
                v-for="part in partList" 
                :key="part.id" 
                :label="`${part.partName} (${part.model})`" 
                :value="part.id" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数量" prop="quantity">
            <el-input-number v-model="requestForm.quantity" :min="1" />
          </el-form-item>
          <el-form-item label="申请原因" prop="reason">
            <el-input v-model="requestForm.reason" type="textarea" rows="3" placeholder="请简要说明申请原因" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitRequest">提交申请</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 申请历史 -->
      <el-card class="history-card">
        <template #header>
          <div class="card-header">
            <span>申请历史</span>
          </div>
        </template>
        <el-table :data="requestHistory" style="width: 100%" v-loading="loading">
          <el-table-column prop="id" label="申请编号" width="120" />
          <el-table-column label="零部件" width="200">
            <template #default="{ row }">
              {{ getPartName(row.partId) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="120" />
          <el-table-column prop="status" label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="申请时间" width="180" />
        </el-table>
      </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { list as listParts } from '@/api/inventory'
import { list as listPartRequests, add } from '@/api/applyrequest'
import { useUserStore } from '@/store/user'
import RepairLayout from './RepairLayout.vue'

const userStore = useUserStore()
const requestFormRef = ref(null)
const loading = ref(false)
const partList = ref([])
const partMap = ref({})

const requestForm = reactive({
  partId: '',
  quantity: 1,
  reason: ''
})

const rules = {
  partId: [{ required: true, message: '请选择零部件', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
  reason: [{ required: true, message: '请输入申请原因', trigger: 'blur' }]
}

const requestHistory = ref([])

const statusMap = {
  0: { text: '待审批', type: 'warning' },
  1: { text: '已通过', type: 'success' },
  2: { text: '已驳回', type: 'danger' }
}

const getStatusText = (status) => {
  return statusMap[status]?.text || '未知状态'
}

const getStatusType = (status) => {
  return statusMap[status]?.type || 'info'
}

const getPartName = (partId) => {
  return partMap.value[partId]?.partName || '未知零部件'
}

const fetchParts = async () => {
  try {
    const res = await listParts()
    partList.value = res
    partMap.value = res.reduce((map, part) => {
      map[part.id] = part
      return map
    }, {})
  } catch (error) {
    console.error('获取零部件列表失败:', error)
    ElMessage.error('获取零部件列表失败')
  }
}

const fetchRequestHistory = async () => {
  loading.value = true
  try {
    const res = await listPartRequests({ userId: userStore.userId })
    requestHistory.value = res
  } catch (error) {
    console.error('获取申请历史失败:', error)
    ElMessage.error('获取申请历史失败')
  } finally {
    loading.value = false
  }
}

const submitRequest = async () => {
  if (!requestFormRef.value) return
  
  try {
    await requestFormRef.value.validate()
    
    const formData = {
      partId: requestForm.partId,
      quantity: requestForm.quantity,
      reason: requestForm.reason,
      userId: userStore.userId
    }
    
    await add(formData)
    ElMessage.success('申请提交成功')
    
    // 重置表单
    requestFormRef.value.resetFields()
    
    // 刷新申请历史
    await fetchRequestHistory()
  } catch (error) {
    if (error.message !== 'validate') {
      console.error('提交申请失败:', error)
      ElMessage.error('提交申请失败')
    }
  }
}

onMounted(() => {
  fetchParts()
  fetchRequestHistory()
})
</script>

<style scoped>
.parts-request-container {
  padding: 20px;
}

.request-card {
  margin-bottom: 20px;
  max-width: 800px;
}

.history-card {
  margin-top: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>